<template>
  <div>
    <span class="text-muted" v-if="!loading && list.length === 0">暂无权限列表</span>

    <el-checkbox-group v-model="innerValue" class="row">
      <el-checkbox
        v-for="auth in list"
        :key="auth.scope_value"
        :label="auth.scope_value"
        class="col-4 m-0"
      >
        <span>{{ auth.scope_name }}</span>
        <span class="text-muted" v-if="auth.is_only_one === 1">(唯一指定)</span>
      </el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script>
const tableName = 'scope_list_view'

export default {
  components: {},
  props: {
    value: {
      type: String,
      default: '',
    },
    orgType: {
      type: String,
      default: 'org_bank',
    },
    authType: {
      type: Number,
      default: 1, // 1外部权限 0内部权限
    },
    filter: {
      type: Function,
      default: () => true,
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  data() {
    return {
      loading: false,
      list: [],
    }
  },
  computed: {
    innerValue: {
      set: function (v = []) {
        const auths = v.join('|')
        const names = v
          .map(it => {
            const temp = this.list.find(authItem => authItem.scope_value === it)
            return temp ? temp.scope_name : ''
          })
          .join('|')
        this.$emit('change', auths, names)
      },
      get: function () {
        return this.value.split('|').filter(it => it)
      },
    },
  },
  watch: {},
  created() {
    this.init()
  },
  mounted() {},
  methods: {
    init() {
      this.loading = true
      this.getAllAuth()
        .then(list => {
          this.list = list.filter(this.filter)
          this.$emit('getAllAuth', this.list)
        })
        .finally(() => {
          this.loading = false
        })
    },

    getAllAuth() {
      return this.$api
        .getData(this.$serviceName, tableName, {
          'is_outside.eq': this.authType,
          'org_class.eq': this.orgType,
        })
        .then(res =>
          (res?.data ?? []).map(it => {
            it.is_only_one = +it.is_only_one
            return it
          })
        )
    },
  },
}
</script>

<style lang="scss" scoped></style>
